import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface OrderItem {
  id: number
  name: string
  image: string
  specText: string
  quantity: number
  price: number
  totalPrice: number
}

export interface OrderData {
  items: OrderItem[]
  totalPrice: number
  address?: {
    name: string
    phone: string
    address: string
  }
  paymentMethod?: string
}

export const useOrderStore = defineStore('order', () => {
  // 订单数据
  const orderData = ref<OrderData>({
    items: [],
    totalPrice: 0,
  })

  // 计算总价
  const totalPrice = computed(() => {
    return orderData.value.items.reduce((total, item) => total + item.totalPrice, 0)
  })

  // 计算商品总数
  const totalQuantity = computed(() => {
    return orderData.value.items.reduce((total, item) => total + item.quantity, 0)
  })

  // 设置订单商品
  const setOrderItems = (items: OrderItem[]) => {
    orderData.value.items = items
    orderData.value.totalPrice = totalPrice.value
  }

  // 添加单个商品到订单
  const addOrderItem = (item: OrderItem) => {
    // 检查是否已存在相同商品
    const existingIndex = orderData.value.items.findIndex(
      (existingItem) => existingItem.id === item.id && existingItem.specText === item.specText,
    )

    if (existingIndex >= 0) {
      // 如果已存在，增加数量
      orderData.value.items[existingIndex].quantity += item.quantity
      orderData.value.items[existingIndex].totalPrice =
        orderData.value.items[existingIndex].price * orderData.value.items[existingIndex].quantity
    } else {
      // 如果不存在，添加新商品
      orderData.value.items.push(item)
    }

    orderData.value.totalPrice = totalPrice.value
  }

  // 设置配送地址
  const setAddress = (address: { name: string; phone: string; address: string }) => {
    orderData.value.address = address
  }

  // 设置支付方式
  const setPaymentMethod = (method: string) => {
    orderData.value.paymentMethod = method
  }

  // 清空订单数据
  const clearOrder = () => {
    orderData.value = {
      items: [],
      totalPrice: 0,
    }
  }

  // 移除订单中的商品
  const removeOrderItem = (index: number) => {
    orderData.value.items.splice(index, 1)
    orderData.value.totalPrice = totalPrice.value
  }

  // 更新商品数量
  const updateItemQuantity = (index: number, quantity: number) => {
    if (quantity > 0) {
      orderData.value.items[index].quantity = quantity
      orderData.value.items[index].totalPrice = orderData.value.items[index].price * quantity
      orderData.value.totalPrice = totalPrice.value
    }
  }

  return {
    orderData,
    totalPrice,
    totalQuantity,
    setOrderItems,
    addOrderItem,
    setAddress,
    setPaymentMethod,
    clearOrder,
    removeOrderItem,
    updateItemQuantity,
  }
})
